<template>
  <div class="admin-qualification">
    <div class="page-header">
      <h1>入围管理</h1>
      <p>管理学生入围名单和发布</p>
    </div>

    <!-- 搜索筛选 -->
    <el-card class="filter-card" shadow="never">
      <el-form :model="searchForm" :inline="true">
        <el-form-item label="院校">
          <el-select v-model="searchForm.schoolId" placeholder="选择院校" clearable>
            <el-option v-for="school in schools" :key="school.id" :label="school.name" :value="school.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="专业">
          <el-select v-model="searchForm.majorId" placeholder="选择专业" clearable>
            <el-option v-for="major in majors" :key="major.id" :label="major.name" :value="major.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="入围类型">
          <el-select v-model="searchForm.qualificationType" placeholder="入围类型" clearable>
            <el-option label="校测入围" value="exam" />
            <el-option label="录取入围" value="admission" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadQualifications">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span>入围名单</span>
          <div>
            <el-button type="primary" @click="generateList">生成名单</el-button>
            <el-button type="success" @click="publishSelected" :disabled="selectedIds.length === 0">
              发布选中
            </el-button>
          </div>
        </div>
      </template>

      <el-table 
        v-loading="loading" 
        :data="qualifications" 
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="studentName" label="学生姓名" />
        <el-table-column prop="idCard" label="身份证号" />
        <el-table-column prop="totalScore" label="总分" sortable />
        <el-table-column prop="rankInMajor" label="专业排名" sortable />
        <el-table-column prop="qualificationType" label="入围类型">
          <template #default="{ row }">
            <el-tag :type="row.qualificationType === 'exam' ? 'primary' : 'success'">
              {{ row.qualificationType === 'exam' ? '校测入围' : '录取入围' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <el-tag :type="row.status === 2 ? 'success' : 'warning'">
              {{ row.status === 2 ? '已发布' : '待发布' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="publishTime" label="发布时间" />
        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <el-button 
              v-if="row.status !== 2" 
              size="small" 
              type="primary" 
              @click="publishSingle(row)"
            >
              发布
            </el-button>
            <el-button size="small" @click="editQualification(row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadQualifications"
          @current-change="loadQualifications"
        />
      </div>
    </el-card>

    <!-- 生成名单对话框 -->
    <el-dialog v-model="generateDialogVisible" title="生成入围名单" width="500px">
      <el-form :model="generateForm" label-width="120px">
        <el-form-item label="选择院校" required>
          <el-select v-model="generateForm.schoolId" placeholder="请选择院校">
            <el-option v-for="school in schools" :key="school.id" :label="school.name" :value="school.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="选择专业" required>
          <el-select v-model="generateForm.majorId" placeholder="请选择专业">
            <el-option v-for="major in generateMajors" :key="major.id" :label="major.name" :value="major.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="入围类型" required>
          <el-select v-model="generateForm.qualificationType">
            <el-option label="校测入围" value="exam" />
            <el-option label="录取入围" value="admission" />
          </el-select>
        </el-form-item>
        <el-form-item label="入围人数" required>
          <el-input-number v-model="generateForm.count" :min="1" :max="1000" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="generateDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmGenerate">确定生成</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '@/api'

// 响应式数据
const loading = ref(false)
const qualifications = ref([])
const schools = ref([])
const majors = ref([])
const generateMajors = ref([])
const selectedIds = ref([])

const searchForm = reactive({
  schoolId: '',
  majorId: '',
  qualificationType: ''
})

const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

const generateDialogVisible = ref(false)
const generateForm = reactive({
  schoolId: '',
  majorId: '',
  qualificationType: 'exam',
  count: 50
})

// 方法
const loadQualifications = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      size: pagination.size,
      ...searchForm
    }
    const { data } = await api.get('/qualification/admin', { params })
    qualifications.value = data.records || []
    pagination.total = data.total || 0
  } catch (error) {
    ElMessage.error('加载失败')
  } finally {
    loading.value = false
  }
}

const loadSchools = async () => {
  try {
    const { data } = await api.get('/schools')
    schools.value = data.records || []
  } catch (error) {
    console.error('加载院校失败:', error)
  }
}

const loadMajors = async () => {
  if (searchForm.schoolId) {
    try {
      const { data } = await api.get('/majors', { 
        params: { schoolId: searchForm.schoolId } 
      })
      majors.value = data.records || []
    } catch (error) {
      console.error('加载专业失败:', error)
    }
  } else {
    majors.value = []
  }
}

const loadGenerateMajors = async () => {
  if (generateForm.schoolId) {
    try {
      const { data } = await api.get('/majors', { 
        params: { schoolId: generateForm.schoolId } 
      })
      generateMajors.value = data.records || []
    } catch (error) {
      console.error('加载专业失败:', error)
    }
  } else {
    generateMajors.value = []
  }
}

const resetSearch = () => {
  Object.assign(searchForm, {
    schoolId: '',
    majorId: '',
    qualificationType: ''
  })
  majors.value = []
  loadQualifications()
}

const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

const generateList = () => {
  Object.assign(generateForm, {
    schoolId: '',
    majorId: '',
    qualificationType: 'exam',
    count: 50
  })
  generateDialogVisible.value = true
}

const confirmGenerate = async () => {
  try {
    await api.post('/qualification/generate', null, {
      params: {
        schoolId: generateForm.schoolId,
        majorId: generateForm.majorId,
        qualificationType: generateForm.qualificationType,
        count: generateForm.count
      }
    })
    ElMessage.success('名单生成成功')
    generateDialogVisible.value = false
    loadQualifications()
  } catch (error) {
    ElMessage.error('名单生成失败')
  }
}

const publishSelected = async () => {
  try {
    await ElMessageBox.confirm('确认发布选中的入围名单？', '确认发布')
    await api.put('/qualification/publish', null, {
      params: { ids: selectedIds.value }
    })
    ElMessage.success('发布成功')
    loadQualifications()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('发布失败')
    }
  }
}

const publishSingle = async (row) => {
  try {
    await ElMessageBox.confirm('确认发布此入围名单？', '确认发布')
    await api.put('/qualification/publish', null, {
      params: { ids: [row.id] }
    })
    ElMessage.success('发布成功')
    loadQualifications()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('发布失败')
    }
  }
}

const editQualification = (row) => {
  ElMessage.info('编辑功能待实现')
}

// 监听
watch(() => searchForm.schoolId, () => {
  searchForm.majorId = ''
  loadMajors()
})

watch(() => generateForm.schoolId, () => {
  generateForm.majorId = ''
  loadGenerateMajors()
})

// 初始化
onMounted(() => {
  loadQualifications()
  loadSchools()
})
</script>

<style lang="scss" scoped>
.admin-qualification {
  .page-header {
    margin-bottom: 20px;
    
    h1 {
      margin: 0 0 8px 0;
      font-size: 24px;
      color: #303133;
    }
    
    p {
      margin: 0;
      color: #909399;
    }
  }
  
  .filter-card {
    margin-bottom: 20px;
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .pagination-wrapper {
    margin-top: 20px;
    text-align: right;
  }
}
</style>